package com.lsh.airticket.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

/**
 * 自定义全局异常处理
 */

@ControllerAdvice
public class GlobalException {


    /**
     * 捕获 自定义用户 异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = {UserException.class}) //遇到异常信息格式是自定义的异常格式时进行处理
    public Object ApiException(UserException e) {
        int code = e.getCode();
        String message = e.getMessage();

        //将异常信息封装成json格式返回给前端
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        modelAndView.addObject("msg", message);
        modelAndView.addObject("status", code);
        return modelAndView;
    }

    @ExceptionHandler(value = {Exception.class}) //遇到异常信息格式是自定义的异常格式时进行处理
    public Object ApiException(Exception e) {
        e.printStackTrace();
        String message = e.getMessage();

        //将异常信息封装成json格式返回给前端
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        modelAndView.addObject("msg", "服务器异常");
        modelAndView.addObject("status", 2);
        return modelAndView;
    }
}
